package net.htjs.juc.chapter06.atomicreference;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

@Slf4j
public class AtomicMarkableAba {

    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag = new GarbageBag("装满了垃圾");
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);
        log.info("main start");
        GarbageBag prev = ref.getReference();
        log.info("main:{}", prev.toString());
        new Thread(() -> {
            log.info("保洁阿姨开始工作");
            bag.setDesc("空垃圾袋");
            ref.compareAndSet(bag, bag, true, false);
            log.info(bag.toString());
        }, "保洁阿姨").start();

        Thread.sleep(1000);
        log.info("想换一只新垃圾袋");
        boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
        log.info("换了新垃圾袋:{}", success);
        log.info("main:{}", ref.getReference().toString());
    }



}
class GarbageBag{

    private String desc;

    public GarbageBag(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return super.toString() + "GarbageBag{" +
                "desc='" + desc + '\'' +
                '}';
    }
}
